const fs = require("fs");
const path = require("path");
const { Sequelize, DataTypes } = require("sequelize");
const config = require("../config/application.config.js");

// 初始化 Sequelize 实例
const sequelize = new Sequelize(config.dbConfig);

// 测试数据库连接
sequelize
  .authenticate()
  .then(() => console.log("Database connected..."))
  .catch((err) => console.error("Unable to connect to the database:", err));

const db = {};

// 动态加载模型
fs.readdirSync(__dirname)
  .filter((file) => {
    return (
      file.indexOf(".") !== 0 && file !== "index.js" && file.slice(-3) === ".js"
    );
  })
  .forEach((file) => {
    const model = require(path.join(__dirname, file))(sequelize, DataTypes);
    db[model.name] = model;
  });

// 调用各模型的 associate 方法定义关联
Object.keys(db).forEach((modelName) => {
  db[modelName]?.associate?.(db);
});

// 加载模型
db.Sequelize = Sequelize;
db.sequelize = sequelize;

// 导出模型
module.exports = db;
